//
//  BaseCustomWindow.swift
//  HealthDetection
//
//  Created by miaokai on 2018/11/28.
//  Copyright © 2018 lianyi. All rights reserved.
//

import UIKit

public enum PopStyle {
    case center
    case bottom
}

/// 自定义的弹框窗口的基类，contentView组成
open class KBaseCustomWindow: UIView {
    
    /// 总的容器
    public var contentView: UIView!
    public var popStyle = PopStyle.center
    public var anDuration: TimeInterval = 0.25
    public var isShow = false
    public var backInteraction = true
    
    // 便利构造器
    public convenience init() {
        self.init(frame: UIScreen.main.bounds)
    }
    
    // 初始化方法
    public override init(frame: CGRect) {
        super.init(frame: frame)
        subViewInit()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:- subViews
    open func subViewInit() {
        self.isUserInteractionEnabled = true
        
        self.backgroundColor = UIColor.black.withAlphaComponent(0)
        let tapGester = UITapGestureRecognizer.init(target: self, action: #selector(tapAction(sender:)))
        tapGester.delegate = self
        self.addGestureRecognizer(tapGester)
        
        
        // 总容器
        contentView = UIView.init(frame: CGRect.zero)
        contentView.autoresizesSubviews = true
        contentView.backgroundColor = UIColor.init(white: 1, alpha: 0.95)
        self.addSubview(contentView)
    }
    
    @objc
    func tapAction(sender: UITapGestureRecognizer) {
        let tapPoint = sender.location(in: self)
        if !contentView.frame.contains(tapPoint) {
            dismiss()
        }
    }
    
    open func dismiss() {
        if backInteraction {
            hide()
        }
    }
    
    /// 弹出
    open func show() {
        UIApplication.shared.keyWindow?.addSubview(self)
        isShow = true
        
        // 监听键盘弹出的事件
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardViewShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardViewHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        switch popStyle {
        case .center:
            contentView.transform = CGAffineTransform.init(scaleX: 1.1, y: 1.1)
            contentView.center = self.center
            contentView.alpha = 0
            UIView.animate(withDuration: anDuration,
                           delay: 0,
                           usingSpringWithDamping: 0.7,
                           initialSpringVelocity: 0.7,
                           options: [UIView.AnimationOptions.curveEaseIn],
                           animations: {
                            self.contentView.transform = CGAffineTransform.init(scaleX: 1, y: 1)
                            self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
                            self.contentView.alpha = 1
            }) { (_) in
                
            }
        case .bottom:
            contentView.top = self.height
            contentView.alpha = 1
            UIView.animate(withDuration: anDuration) {
                var frame = self.contentView.frame
                frame.origin.y = self.height -
                    frame.height
                self.contentView.frame = frame
                self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            }
        }
    }
    
    /// 隐藏
    @objc open func hide() {
        isShow = false
        UIView.animate(withDuration: anDuration, delay: 0, options: .curveEaseOut, animations: {
            self.backgroundColor = UIColor.black.withAlphaComponent(0)
            switch self.popStyle {
            case .center:
                self.contentView.transform = CGAffineTransform.init(scaleX: 0.8, y: 0.8)
                self.contentView.alpha = 0
            case .bottom:
                self.contentView.top = self.height
            }
            
        }) { (_) in
            self.removeFromSuperview()
            NotificationCenter.default.removeObserver(self)
        }
    }
    
    // 键盘即将隐藏
    @objc open func keyBoardViewShow(_ notification: Notification) {
        let info = notification.userInfo
        let value = info![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let height = value.size.height
        
        UIView.animate(withDuration: 0.15) {
            self.contentView.bottom = self.height - height
            self.layoutIfNeeded()
        }
    }
    
    // 键盘即将弹出
    @objc open func keyBoardViewHide(_ notification: Notification) {
        UIView.animate(withDuration: 0.15) {
            self.contentView.center = self.center
            self.layoutIfNeeded()
        }
    }
    
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.endEditing(true)
    }
}

extension KBaseCustomWindow: UIGestureRecognizerDelegate {
    // superView的tap事件会和tableView，collectionView的点击事件冲突，在此来解决冲突
    // 在tap的代理中，判断点击视图的类型是table或者collection的话不响应事件
    open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if let touchClassCoder = touch.view?.classForCoder,
            let supClassCoder = touch.view?.superview?.superview?.classForCoder  {
            
            let touchClass = NSStringFromClass(touchClassCoder)
            let supClass = NSStringFromClass(supClassCoder)
            
            if touchClass == "UITableView" || touchClass == "UICollectionView" || supClass == "UITableView" || supClass == "UICollectionView" {
                return false
            } else if touchClass == "UITableViewCellContentView", supClass == "UITableViewWrapperView" { // iOS 9.0
                return false
            }
        }
        return true
    }
}

